package org.firebug.spring.cloud.oauth2.service;

import org.firebug.spring.cloud.oauth2.repository.dao.UserDAO;
import org.firebug.spring.cloud.oauth2.repository.po.UserPO;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserDAO userDAO;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserPO po = userDAO.selectByUsername(username);
        if (po == null) {
            throw new UsernameNotFoundException(username);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList();
        if (!StringUtils.isEmpty(po.getRoles())) {
            for (String role : po.getRoles().split(",")) {
                if (!StringUtils.isEmpty(role)) {
                    authorities.add(new SimpleGrantedAuthority(role.trim()));
                }
            }
        }
        return new User(po.getUsername(), po.getPassword(), authorities);
    }
}
